/***************************************************************************
 *   Copyright (C) 2008 by Ryszard Krol   *
 *   rysiek.krol@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include <QtGui>
#include "picturemanager.h"
#include "imagereader.h"
#include "renamedialog.h"
#include "updateiconevent.h"
#include "picturelistwidgetitem.h"
#include "imageloadedevent.h"
#include "imageloader.h"
#include "updatestatusbarevent.h"
#include "commentdialog.h"
#include "propertydialog.h"
#include "fileoperationshandler.h"
#include "progressdialogevent.h"
#include "progressbardialogs.h"
#include "displayoperations.h"
#include "saveimageevent.h"
#include "eventhandler.h"
#include "presentationwindow.h"
#include "filesoperations.h"
#include "iconprovider.h"
#include "alicefilesystemmodel.h"

#include <QCloseEvent>
#include <QFileDialog>
#include <QListWidget>
#include <QDir>
#include <QMenu>
#include <QPixmap>
#include <QMutex>
#include <QWidget>
#include <QSplitter>
#include <QTreeView>
#include <QList>
#include <QStyle>
#include <QScrollArea>
#include <QKeyEvent>


/**
* Class constructor
*/
PictureManager::PictureManager(QStyle *styl)
{
    this->itsProperty = new Property();
    this->curDir = new QDir(this->itsProperty->getPictureDir());
    this->oldDir = new QDir(this->itsProperty->getPictureDir());
    initializeGUI(styl);
    this->switchGuiToBrowserMode();
    this->isAlbumViewer = false;
}

/**
* Class constructor
*/
PictureManager::PictureManager(QStyle * styl, QString filePath)
{
    if (filePath.endsWith("\n")) filePath.chop(2);
    if (filePath.endsWith("\t")||filePath.endsWith(" ")) filePath.chop(1);
    QFileInfo *pliczek = new QFileInfo(filePath);
    this->itsProperty = new Property();
    if (pliczek->exists())
    {
        this->curDir = new QDir(pliczek->dir());
        this->oldDir = new QDir(pliczek->dir());
        initializeGUI(styl);
        this->switchGuiToPresentationMode(pliczek);
        this->isAlbumViewer = false;
    }
    else
    {
        this->curDir = new QDir();
        this->oldDir = new QDir();
        initializeGUI(styl);
        this->switchGuiToBrowserMode();
        this->isAlbumViewer = false;
    }
    delete pliczek;
}
/**
* Build GUI
*/

void PictureManager::initializeGUI(QStyle * styl)
{
    this->setStyl(styl);
    this->buildBrowserWidget();
    //tworzenie glownego okna
    this->setCentralWidget ( this->browserWidget);
    this->itsReader =  new ImageReader ( this, this->curDir );
    this->isPresentationMode = false;
    this->displayOperations = new DisplayOperations(this);
    this->filesOperations = new FilesOperations(this);
    createActions();
    createMenus();
    createToolBars();
    createStatusBar();
    this->move(this->itsProperty->getWindowPosition());
    this->resize(this->itsProperty->getWindowSize());
    //Ustawianie Tytulu

    this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
    this->itsLoader = new ImageLoader(this);
    this->itsEventHandler = new EventHandler(this);
    this->fullScreen = false;
    this->progressBarDialogs = new ProgressBarDialogs();

}

/**
 * Building About dialog
 */
void PictureManager::about()
{

    QMessageBox::about ( this, tr ( "About Application" ),
                         tr("Multi-platform picture manager" ) );

}
/**
 * Creates Actions
 */
void PictureManager::createActions()
{

    renameAct = new QAction ( tr ( "&Rename" ), this );
    renameAct->setShortcut ( tr ( "Ctrl+R" ) );
    renameAct->setStatusTip ( tr ( "Change file name" ) );
    connect ( renameAct, SIGNAL ( triggered() ), this, SLOT ( renameDialog() ) );

    exitAct = new QAction ( tr ( "E&xit" ), this );
    exitAct->setShortcut ( tr ( "Ctrl+Q" ) );
    exitAct->setStatusTip ( tr ( "Exit the application" ) );
    connect ( exitAct, SIGNAL ( triggered() ), this, SLOT ( close() ) );

    aboutAct = new QAction ( tr ( "&About" ), this );
    aboutAct->setStatusTip ( tr ( "Show the application's About box" ) );
    connect ( aboutAct, SIGNAL ( triggered() ), this, SLOT ( about() ) );

    aboutQtAct = new QAction ( tr ( "About &Qt" ), this );
    aboutQtAct->setStatusTip ( tr ( "Show the Qt library's About box" ) );
    connect ( aboutQtAct, SIGNAL ( triggered() ), qApp, SLOT ( aboutQt() ) );

    connect (this->treeWidget, SIGNAL (clicked(const QModelIndex & )) , this, SLOT (treeClicked(const QModelIndex & )));
    connect ( this->listWidget, SIGNAL ( itemDoubleClicked ( QListWidgetItem * ) ), this, SLOT ( listClicked ( QListWidgetItem * ) ) );

    closePresentaionAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_DialogCloseButton), tr ( "&Close" ), this );
    closePresentaionAct->setStatusTip ( tr ( "Close Image" ) );
    connect ( closePresentaionAct, SIGNAL ( triggered() ), this, SLOT ( switchGuiToBrowserMode() ) );

    displayNextImageAct = new QAction (QIcon(":/nextImage"),tr ( "&Next" ), this );
    displayNextImageAct->setStatusTip ( tr ( "Next Image" ) );
    connect ( displayNextImageAct, SIGNAL ( triggered() ), this->displayOperations, SLOT ( displayNextImage() ) );

    displayPreviousImageAct = new QAction (QIcon(":/previousImage"),tr ( "&Previous" ), this );
    displayPreviousImageAct->setStatusTip ( tr ( "Previouse Image" ) );
    connect ( displayPreviousImageAct, SIGNAL ( triggered() ), this->displayOperations, SLOT ( displayPreviousImage() ) );

    goBackAct = new QAction (QIcon(":/previousDir"),tr ( "&Back" ), this );
    goBackAct->setStatusTip ( tr ( "Go to previous directory" ) );
    connect ( goBackAct, SIGNAL ( triggered() ), this, SLOT ( goBackSlot() ) );

    this->goUpAct = new QAction (QIcon(":/upDir"),tr ( "&Up" ), this );
    this->goUpAct->setStatusTip ( tr ( "Go to upper directory" ) );
    connect ( this->goUpAct, SIGNAL ( triggered() ), this, SLOT ( goUpSlot() ) );

    this->reLoadBrowserAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_BrowserReload),tr ( "&Reload" ), this );
    this->reLoadBrowserAct->setStatusTip ( tr ( "Reload view" ) );
    connect ( this->reLoadBrowserAct, SIGNAL ( triggered() ), this, SLOT ( reLoadSlot() ) );

    this->goToFullScreenAct = new QAction (QIcon(":/window_fullscreen.png"),tr ( "&Full Screen" ), this );
    this->goToFullScreenAct->setStatusTip ( tr ( "Show picture in Full Screen" ) );
    connect ( this->goToFullScreenAct, SIGNAL ( triggered() ), this, SLOT ( fullScreenSwichSlot() ) );

    this->commentEditAct = new QAction (QIcon(":/editComment"),tr ( "&Edit Comment" ), this );
    this->commentEditAct->setStatusTip ( tr ( "Edit Picture Comments" ) );
    connect ( this->commentEditAct, SIGNAL ( triggered() ), this, SLOT ( editComment() ) );

    this->commentRemoveAct = new QAction (QIcon(":/removeComments"),tr ( "&Remove comment" ), this );
    this->commentRemoveAct->setStatusTip ( tr ( "Remove picture's comment" ) );
    connect ( this->commentRemoveAct, SIGNAL ( triggered() ), this, SLOT ( removeCommentSlot() ) );

    this->PropertyDialogOpenAct = new QAction (tr ( "&Properties" ), this );
    this->PropertyDialogOpenAct->setStatusTip ( tr ( "Application Settings" ) );
    connect ( this->PropertyDialogOpenAct, SIGNAL ( triggered() ), this, SLOT ( PropertyDialogOpenSlot() ) );

    this->removeFilesAct = new QAction (tr ( "&Delete" ), this );
    this->removeFilesAct->setStatusTip ( tr ( "Delete selected files" ) );
    connect ( this->removeFilesAct, SIGNAL ( triggered() ), this->filesOperations, SLOT ( deleteFilesSlot() ) );

    this->copyFilesAct = new QAction (QIcon(":/copyFiles"),tr ( "&Copy to" ), this );
    this->copyFilesAct->setStatusTip ( tr ( "Copy selected files to given directory" ) );
    connect ( this->copyFilesAct, SIGNAL ( triggered() ), this->filesOperations, SLOT ( copyFilesSlot() ) );

    this->moveFilesAct = new QAction (QIcon(":/moveFiles"), tr ( "&Move" ), this );
    this->moveFilesAct->setStatusTip ( tr ( "Move selected files" ) );
    connect ( this->moveFilesAct, SIGNAL ( triggered() ), this->filesOperations, SLOT ( moveFilesSlot() ) );

    this->makeDirectoryAct = new QAction (QIcon(":/newDir"), tr ( "&Make Directory" ), this );
    this->makeDirectoryAct->setStatusTip ( tr ( "Make New Direcotry" ) );
    connect ( this->makeDirectoryAct, SIGNAL ( triggered() ), this, SLOT ( makeDirectorySlot() ) );

    this->rotate90Act = new QAction (QIcon(":/rotate90"), tr ( "Rotate 90 degree" ), this );
    this->rotate90Act->setStatusTip ( tr ( "Rotates 90 degree cloackwise" ) );
    connect ( this->rotate90Act, SIGNAL ( triggered() ), this->displayOperations, SLOT ( rotateImage90() ) );

    this->rotate180Act = new QAction (QIcon(":/rotate180"), tr ( "Rotate 180 degree" ), this );
    this->rotate180Act->setStatusTip ( tr ( "Rotates 180 degree cloackwise" ) );
    connect ( this->rotate180Act, SIGNAL ( triggered() ), this->displayOperations, SLOT ( rotateImage180() ) );

    this->rotate270Act = new QAction (QIcon(":/rotate270"), tr ( "Rotate 270 degree" ), this );
    this->rotate270Act->setStatusTip ( tr ( "Rotates 270 degree cloackwise" ) );
    connect ( this->rotate270Act, SIGNAL ( triggered() ), this->displayOperations, SLOT ( rotateImage270() ) );

    this->saveImageAct = new QAction (QIcon(":/save"), tr ( "&Save" ), this );
    this->saveImageAct->setStatusTip ( tr ( "Save changed image" ) );
    this->saveImageAct->setShortcut ( tr ( "Ctrl+S" ) );
    connect ( this->saveImageAct, SIGNAL ( triggered() ), this, SLOT ( saveImageSlot() ) );

    this->slideShowAct = new QAction (QIcon(":/slideshow"), tr ( "S&lideShow" ), this );
    this->slideShowAct->setStatusTip ( tr ( "Run Slide Show" ) );
    connect ( this->slideShowAct, SIGNAL ( triggered() ), this->displayOperations, SLOT ( slideShowSlot() ) );

    this->keywordsAct = new QAction (QIcon(":/keywords"), tr ( "&Keywords" ), this );
    this->keywordsAct->setStatusTip ( tr ( "Manage keywords" ) );
    connect ( this->keywordsAct, SIGNAL ( triggered() ), this->displayOperations, SLOT ( keywordsSlot() ) );
    
    this->searchAct = new QAction (tr ( "&Search" ), this );
    this->searchAct->setStatusTip ( tr ( "Find Images" ) );
    connect ( this->searchAct, SIGNAL ( triggered() ), this->displayOperations, SLOT ( searchSlot() ) );

    this->imagePropertyDialogAct = new QAction(tr("Image Properties"), this);
    this->imagePropertyDialogAct->setStatusTip(tr("Open image properties dialog"));
    connect (this->imagePropertyDialogAct, SIGNAL (triggered()), this->displayOperations, SLOT(imagePropertiesSlot()));

    this->copyAct = new QAction(tr("Copy"), this);
    this->copyAct->setStatusTip(tr("Copy selected files"));
    this->copyAct->setShortcut ( tr ( "Ctrl+c" ) );
    connect (this->copyAct, SIGNAL (triggered()), this->filesOperations, SLOT(copySlot()));

    this->cutAct = new QAction(tr("Cut"), this);
    this->cutAct->setStatusTip(tr("Cut selected files"));
    this->cutAct->setShortcut ( tr ( "Ctrl+x" ) );
    connect (this->cutAct, SIGNAL (triggered()), this->filesOperations, SLOT(cutSlot()));

    this->pasteAct = new QAction(tr("Paste"), this);
    this->pasteAct->setStatusTip(tr("Paste files"));
    this->pasteAct->setShortcut ( tr ( "Ctrl+v" ) );
    connect (this->pasteAct, SIGNAL (triggered()), this->filesOperations, SLOT(pasteSlot()));

    connect(this->treeWidget, SIGNAL(doubleClicked(const QModelIndex&)),
            this, SLOT(treeClicked(const QModelIndex&)));

    QObject::connect(this->listView, SIGNAL(doubleClicked(const QModelIndex&)),
                     this->listView, SLOT(setRootIndex(const QModelIndex&)));
    // update tree upon list change
    QObject::connect(this->listView, SIGNAL(doubleClicked(const QModelIndex&)),
                     this, SLOT(listClicked(const QModelIndex&)));

}

/**
 * Building Menus
 */
void PictureManager::createMenus()
{
    fileMenu = menuBar()->addMenu ( tr ( "&File" ) );
    fileMenu->addAction ( exitAct );

    editMenu = menuBar()->addMenu ( tr ( "&Edit" ) );
    editMenu->addAction ( renameAct );
    editMenu->addAction ( this->renameAct );
    editMenu->addAction ( this->removeFilesAct);
    editMenu->addAction ( this->copyFilesAct );
    editMenu->addAction (this->moveFilesAct);
    editMenu->addAction (this->makeDirectoryAct);
    editMenu->addSeparator();
    editMenu->addAction(this->copyAct);
    editMenu->addAction(this->cutAct);
    editMenu->addAction(this->pasteAct);
    editMenu->addSeparator();
    editMenu->addAction( this->searchAct);
    editMenu->addSeparator();
    editMenu->addAction(PropertyDialogOpenAct);
    editMenu->addSeparator();

    QMenu *rotateMenu = editMenu->addMenu(tr("Rotate"));
    rotateMenu->addAction(this->rotate90Act);
    rotateMenu->addAction(this->rotate180Act);
    rotateMenu->addAction(this->rotate270Act);

    menuBar()->addSeparator();

    helpMenu = menuBar()->addMenu ( tr ( "&Help" ) );
    helpMenu->addAction ( aboutAct );
    helpMenu->addAction ( aboutQtAct );


}

/**
 * Building Tool Bars
 */
void PictureManager::createToolBars()
{
    this->browserToolBar = this->addToolBar ( tr ( "BrowserToolBar" ) );
    this->browserToolBar->addAction(this->goBackAct);
    this->browserToolBar->addAction(this->goUpAct);
    this->browserToolBar->addAction(this->reLoadBrowserAct);
    this->browserToolBar->addAction(this->slideShowAct);
    this->browserToolBar->setVisible(false);
    
    this->presentationToolBar = this->addToolBar ( tr ( "PresentationToolBar" ) );
    this->presentationToolBar->addAction(this->closePresentaionAct);
    this->presentationToolBar->addSeparator();
    this->presentationToolBar->addAction(this->displayPreviousImageAct);
    this->presentationToolBar->addAction(this->displayNextImageAct);
    this->presentationToolBar->addAction(this->goToFullScreenAct);
    presentationToolBar->setVisible(false);

    this->imageManipulationToolBar = this->addToolBar(tr("ImageManipulationToolBar"));
    this->imageManipulationToolBar->addAction(this->rotate90Act);
    this->imageManipulationToolBar->addAction(this->rotate180Act);
    this->imageManipulationToolBar->addAction(this->rotate270Act);
    this->imageManipulationToolBar->addAction(this->saveImageAct);
    this->imageManipulationToolBar->addAction(this->imagePropertyDialogAct);
    this->imageManipulationToolBar->setVisible(false);
    
    this->commentToolBar = this->addToolBar(tr("CommentToolBar"));
    this->commentToolBar->addAction(this->commentEditAct);
    this->commentToolBar->addAction(this->keywordsAct);
    
    this->sortingToolBar = this->addToolBar(tr("SortingToolBar"));
    
    this->sortingCombo = new QComboBox();
    this->sortingCombo->addItem(tr("Sort by comment date"));
    this->sortingCombo->addItem(tr("Sort by file name"));
    this->sortingCombo->setCurrentIndex(this->itsProperty->getSortMethod());
    this->sortingMethodChangedAct = this->sortingToolBar->addWidget(this->sortingCombo);
    this->sortingToolBar->setVisible(true);
    connect ( this->sortingCombo, SIGNAL ( currentIndexChanged ( int ) ), this, SLOT ( sortingMethodChangedSlot(int) ) );
    
}

/**
 * Building Status Bar
 */
void PictureManager::createStatusBar()
{
    statusBar()->showMessage ( tr ( "Ready" ) );
}

/**
 * Class Destructor
 */
PictureManager::~PictureManager()
{
    delete this->displayOperations;
    delete this->curDir;
    delete this->oldDir;
}

/**
 * Returns ListWidget
 */
QListWidget* PictureManager::getListWidget()
{
    return this->listWidget;
}

/**
 * Handles Custom Events
 */
void PictureManager::customEvent ( QEvent *event )
{
    switch (event->type())
    {
    case ViewerEvent::ListRefreshNeeded:
    case ViewerEvent::UpdateIcon:
    case ViewerEvent::iconGenerationCompleateEvent:
    case ViewerEvent::LoadedImageEvent:
        this->itsEventHandler->handleEvent(event);
        break;
    case ViewerEvent::UpdateStatusBar:
    {
        UpdateStatusBarEvent *updateEvent = dynamic_cast<UpdateStatusBarEvent*>(event);
        this->statusBar()->showMessage ( *updateEvent->getStatus() );
    }
    break;
    case ViewerEvent::ForceReload:
    {
        if (this->isPresentationMode)
        {
            this->displayOperations->displayCorrectImage();
        }
        else
        {
            this->reLoadSlot();
        }
        break;
    }
    case ViewerEvent::ProgressDialogUpdate:
    {
        ProgressDialogEvent *updateEvent = dynamic_cast<ProgressDialogEvent*>(event);
        this->progressBarDialogs->attendValue(updateEvent);
    }
    break;
    case ViewerEvent::SaveImageEvent:
    {
        SaveImageEvent *saveImageEvent = dynamic_cast<SaveImageEvent*>(event);
        new FileOperationsHandler(this, FileOperationsHandler::SaveTransformedImage, saveImageEvent->getFile(), saveImageEvent->getActionList(), false);
    }
    break;
    default:
        QMainWindow ( event );
        break;
    }
}

/**
 * Manage listClicked event
 */
void PictureManager::listClicked ( QListWidgetItem * item )
{
    PictureListWidgetItem *pItem= dynamic_cast<PictureListWidgetItem*>(item);

    QFileInfo *fileInfo = new QFileInfo ( pItem->getFile() );
    this->listClicked(fileInfo);

}

void PictureManager::listClicked (  const QModelIndex & index ){
 QFileInfo *fileInfo = new QFileInfo((dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->fileInfo(index));
 this->listClicked(fileInfo);
}


void PictureManager::listClicked ( QFileInfo *fileInfo ){
    if ( fileInfo->isDir() )
    {
        *this->oldDir = *this->curDir;
        QModelIndex index;
        if ( fileInfo->fileName() == ".." )
        {
            index=(dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->index( curDir->path());
            this->treeWidget->collapse(index);
            curDir->cdUp();
            index=(dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->index( curDir->path());
        }
        else
        {
            curDir->cd ( fileInfo->fileName() );
            index=(dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->index( curDir->path());
            this->treeWidget->expand(index);

        }
        this->treeWidget->setCurrentIndex(index);
        this->reLoadBrowser();
    }
    else
    {
        this->switchGuiToPresentationMode(fileInfo);
    }
    delete fileInfo;
}

/**
 * Displays Context Menu
 */
void PictureManager::contextMenuEvent ( QContextMenuEvent *event )
{
    this->displayOperations->handleContextMenu(event);
}

/**
 * Manage TreeClickedEvent
 */
void PictureManager::treeClicked( const QModelIndex & index )
{
    QFileInfo fileInfo =(dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->fileInfo(index);
    if ( fileInfo.isDir() )
    {
    	this->setIsAlbumViewer(false);
        *this->oldDir = *this->curDir;
        if (fileInfo.absoluteFilePath () != curDir->absolutePath () )
        {
            curDir->cd ( fileInfo.absoluteFilePath () );
            this->reLoadBrowser();
        }
    }
}

/**
 * Renameing files
 */
void PictureManager::renameDialog()
{
    this->filesOperations->renameDialog();
}
/**
 * Returns application style
 */
QStyle * PictureManager::getStyl()
{
    return styl;
}
/**
 * Sets application style
 */
void PictureManager::setStyl( QStyle *theValue)
{
    styl = theValue;
}
/**
* Builds main widget
*/
void PictureManager::buildBrowserWidget()
{
    //Tworzenie Drzewka
    QStringList *filters = new QStringList();
    *filters << "[A-Z, A-Z, 0-9]*" ;
    QFileSystemModel *treeModel = new QFileSystemModel ();
    treeModel->setNameFilters(*filters);
    treeModel->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);
    treeModel->setRootPath(QDir::rootPath());
    this->treeWidget = new QTreeView();
    this->treeWidget->setUpdatesEnabled(true);
    this->treeWidget->setModel ( treeModel );
    QDir w = *this->curDir;
    QModelIndex index = treeModel->index ( w.path());
    this->treeWidget->setColumnHidden(1, true);
    this->treeWidget->setColumnHidden(2, true);
    this->treeWidget->setColumnHidden(3, true);
    this->treeWidget->setCurrentIndex(index);
    this->treeWidget->setVisible(false);
    while ( w.cdUp() )
    {
        QModelIndex index = treeModel->index ( w.path() );
        this->treeWidget->expand ( index );
    }
    // Tworzenie splittera
    this->browserWidget = new QSplitter();
    //tworzenie Okna ikon
    this->listWidget = new QListWidget();
    this->listWidget->setViewMode ( QListView::IconMode );
    this->listWidget->setIconSize ( QSize ( 100, 100 ) );
    this->listWidget->setResizeMode ( QListView::Adjust );
    this->listWidget->setSpacing ( 20 );
    this->listWidget->setGridSize ( QSize ( 150, 180 ) );
    this->listWidget->setMovement ( QListView::Snap );
    this->listWidget->setSelectionMode ( QAbstractItemView::ExtendedSelection );
    this->listWidget->setVisible(false);

    this->scrollArea = new QScrollArea();
    this->scrollArea->setVisible(false);
    this->scrollArea->setWidgetResizable(true);
    this->presentationWidget = new QLabel(tr ("Loading Image..."));
    this->presentationWidget->setAlignment(Qt::AlignCenter);
    this->presentationWidget->setAutoFillBackground(true);

    this->scrollArea->setWidget(this->presentationWidget);


    //tworzenie okna z ikonami
    AliceFileSystemModel *iconModel = new AliceFileSystemModel ();
    QStringList iconfilters;
    iconfilters << "*.jpg" << "*.png" << "*.bmp"<<"*.jpeg"<<"*.JPG"<<"*.JPEG";
    iconModel->setFilter(QDir::AllDirs | QDir::NoDot | QDir::Files);
    iconModel->setNameFilters(iconfilters);
    iconModel->setNameFilterDisables(false);
    iconModel->setRootPath(QDir::rootPath());
    iconModel->setIconProvider(new IconProvider(this));
    index = iconModel->index ( this->curDir->absolutePath());
    this->listView = new QListView();
    this->listView->setViewMode(QListView::IconMode);
    this->listView->setDragEnabled(true);
    this->listView->setModel(iconModel);
    this->listView->setIconSize ( QSize ( 100, 100 ) );
    this->listView->setResizeMode ( QListView::Adjust );
    this->listView->setSpacing ( 20 );
    this->listView->setGridSize ( QSize ( 150, 180 ) );
    this->listView->setMovement ( QListView::Snap );
    this->listView->setSelectionMode ( QAbstractItemView::ExtendedSelection );
    this->listView->setRootIndex(index);

    //Dodawanie drzewa i okna ikon do kontenera
    this->browserWidget->addWidget(this->treeWidget);
    //this->browserWidget->addWidget(this->listWidget);
    this->browserWidget->addWidget(this->listView);
    this->browserWidget->addWidget(this->scrollArea);
    this->browserWidget->setStretchFactor(1,3);

    delete filters;
}

/**
 * Switches GUI to Presentation mode
 */
void PictureManager::switchGuiToPresentationMode(QFileInfo *fileInfo)
{
    if (!this->displayOperations->getIsSlideShowActive())
    {
        while (this->itsReader->getReadingDir()==true) ; //czekaj, jak reader wczyta katalog do listWidgeta
        this->loadImage(this->findItem(fileInfo));

    }
    PictureListWidgetItem *item = new PictureListWidgetItem(*fileInfo);
    this->presentationWidget->setToolTip(item->toolTip());
    delete item;
    this->treeWidget->setVisible(false);
    this->listWidget->setVisible(false);
    this->browserToolBar->setVisible(false);
    this->sortingToolBar->setVisible(false);
    this->sortingMethodChangedAct->setVisible(false);
    this->presentationToolBar->setVisible(true);
    this->imageManipulationToolBar->setVisible(true);
    this->scrollArea->setVisible(true);
    this->setIsPresentationMode(true);
}

/**
 * Switches GUI to Browser mode
 */
void PictureManager::switchGuiToBrowserMode()
{
    this->displayOperations->setIsSlideShowActive(false);
    this->scrollArea->setVisible(false);
    this->presentationToolBar->setVisible(false);
    this->imageManipulationToolBar->setVisible(false);
    this->browserToolBar->setVisible(true);
    this->treeWidget->setVisible(true);
    this->listWidget->setVisible(true);
    this->sortingToolBar->setVisible(true);
    this->sortingMethodChangedAct->setVisible(true);
    this->sortingMethodChangedAct->setEnabled(true);
    this->setIsPresentationMode(false);
    this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
    this->displayOperations->clearSlideList();

    QApplication::postEvent ( this->displayOperations, new ViewerEvent ( ViewerEvent::ScrollToCurrentEvent ));
}

/**
 * Display image from fileInfo via presentationWidget
 */
void PictureManager::displayImage ( QPixmap pixmap )
{
    QSize size = this->browserWidget->size();
    if ( size.width() >pixmap.size().width() && size.height() >pixmap.size().height() )
    {
        this->presentationWidget->setPixmap ( pixmap );
        if ( this->fullScreen )
        {
            this->itsPesentationWindow->setImage(pixmap);
        }
    }
    else
    {
        if ( this->fullScreen )
        {
            this->itsPesentationWindow->setImage(pixmap);
        }
        if ( size.height() >size.width() )
        {
            size.scale ( size.width()-5,size.height()-10, Qt::KeepAspectRatio );
        }
        else
        {
            size.scale ( size.width()-5,size.height()-10, Qt::KeepAspectRatio );
        }
        this->presentationWidget->setPixmap ( pixmap.scaled ( size, Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
    }
}


/**
* Returns index position in ListWidget of file in fileinfo parameter
*/
int PictureManager::findItem(QFileInfo * fileInfo)
{
    for (int i = 0; i<this->listWidget->count(); i++)
    {
        PictureListWidgetItem *item = dynamic_cast<PictureListWidgetItem*> ( this->getListWidget()->item(i));

        if (item->getFile().absoluteFilePath() == fileInfo->absoluteFilePath())return i;
    }
    return -1;
}

/**
* Sets new Index in Loader Thread and wakes it
*/
void PictureManager::loadImage(int index)
{
    this->itsLoader->setCurrentIndex(index);
    this->itsLoader->setGoToSleepFalse();
    this->itsLoader->setCurrentAction(ImageLoader::GetIndex);
    this->itsLoader->newActionCondition.wakeAll();
}

/**
* Goes to Presentation Widget
*/
QLabel* PictureManager::getPresentationWidget() const
{
    return presentationWidget;
}

/**
* Goes to previous directory
*/
void PictureManager::goBackSlot()
{
    this->setIsAlbumViewer(false);
    if (this->curDir!=this->oldDir)
    {
        QDir tmp = *this->curDir;
        *this->curDir = *this->oldDir;
        *this->oldDir = tmp;
        this->reLoadSlot();
    }
}

/**
* Goes to upper directory
*/
void PictureManager::goUpSlot()
{
    this->setIsAlbumViewer(false);
    *this->oldDir = *this->curDir;
    curDir->cdUp();
    QModelIndex index=(dynamic_cast<QFileSystemModel*>(this->treeWidget->model()))->index( curDir->path());
    this->treeWidget->collapse(index);
    this->treeWidget->setCurrentIndex(index);
    this->reLoadBrowser();
}

/**
* Reloads Browser view's
*/
void PictureManager::reLoadSlot()
{
    //QFileSystemModel *index=dynamic_cast<QFileSystemModel*>(this->treeWidget->model());
    //index->refresh();
    PictureListWidgetItem *item = dynamic_cast<PictureListWidgetItem*>(this->listWidget->currentItem());
    if (item != '\0') this->itsProperty->setCurrentItem(item->getFile());
    // reload Album
    if(this->getIsAlbumViewer()){
    	QList<QListWidgetItem*> *widgetList = new QList<QListWidgetItem*>(this->listWidget->findItems(QString("*"), Qt::MatchWrap | Qt::MatchWildcard));
        QList<PictureListWidgetItem*> *pictureList = new QList<PictureListWidgetItem*>();
        for(QList<QListWidgetItem*>::iterator it = widgetList->begin(); it != widgetList->end(); it++)
    		pictureList->append(new PictureListWidgetItem(dynamic_cast<PictureListWidgetItem*>(*it)));
        this->itsReader->setWidgetList(pictureList);
    	this->itsReader->setAction(ImageReader::SortItems);
    }
    this->itsReader->setIsActive(false);
    this->listWidget->clear();
    this->itsReader->setDir(this->curDir);
    this->itsReader->readDirCondition.wakeAll();
    this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
    this->treeWidget->update();
}

/**
* Switching to full screen and to normal view
*/
void PictureManager::fullScreenSwichSlot()
{
    if (getIsPresentationMode())
    {
        if (this->fullScreen)
        {
            this->fullScreen = false;
        }
        else
        {
            this->itsPesentationWindow = new PresentationWindow(this);
            if (this->presentationWidget->pixmap() != 0)
            {
                this->itsPesentationWindow->setImage(*this->presentationWidget->pixmap());
            }
            this->itsLoader->setCurrentAction(ImageLoader::GetCurrent);
            this->itsLoader->setGoToSleepFalse();
            this->itsLoader->newActionCondition.wakeAll();
            this->itsPesentationWindow->show();
            this->fullScreen = true;

        }
    }
}

/**
* Handles KeyPressed Event
*/
void PictureManager::keyPressEvent(QKeyEvent * event)
{
    if (getIsPresentationMode())
    {
        switch (event->key())
        {
        case Qt::Key_F :
            this->fullScreenSwichSlot();
            break;
        case Qt::Key_Space :
        case Qt::Key_Return :
        case Qt::Key_Enter :
            this->displayOperations->displayNextImage();
            break;
        case Qt::Key_Backspace:
            this->displayOperations->displayPreviousImage();
            break;
        case Qt::Key_Delete :
            this->filesOperations->deleteFilesSlot();
            break;
        case Qt::Key_BracketRight:
            this->displayOperations->rotateImage90();
            break;
        case Qt::Key_BracketLeft:
            this->displayOperations->rotateImage270();
            break;
        case Qt::Key_Escape:
            this->switchGuiToBrowserMode();
            break;
        }
    }
    else
    {
        switch (event->key())
        {
        case Qt::Key_Delete :
            this->filesOperations->deleteFilesSlot();
        }
    }
}

/**
* Handles Resize Event
*/
void PictureManager::resizeEvent(QResizeEvent * event)
{
    if (getIsPresentationMode() && event->oldSize().isValid())
    {
        this->itsLoader->setCurrentAction(ImageLoader::GetCurrent);
        this->itsLoader->setGoToSleepFalse();
        this->itsLoader->newActionCondition.wakeAll();
    }
    else
    {
        event->accept();
    }
}

/**
* Returns if program is in Presentation Mode
*/
bool PictureManager::getIsPresentationMode() const
{
    return isPresentationMode;
}

/**
* Sets isPresentationMode Variable
*/
void PictureManager::setIsPresentationMode(bool theValue)
{
    isPresentationMode = theValue;
}

/**
* Handles MousePressed Event
*/
void PictureManager::mousePressEvent(QMouseEvent * event)
{
    if (getIsPresentationMode())
    {
        switch (event->button())
        {
        case Qt::LeftButton:
            this->displayOperations->displayNextImage();
            break;
        case Qt::RightButton:
            this->displayOperations->displayPreviousImage();
            break;
        default:
            break;
        }
    }
}

/**
* Handles Wheel Event
*/
void PictureManager::wheelEvent(QWheelEvent * event)
{
    if (this->getIsPresentationMode())
    {
        if (event->delta()>0 && event->delta()>15)
        {
            this->displayOperations->displayPreviousImage();
        }
        else if (event->delta()<0 && event->delta()<-15)
        {
            this->displayOperations->displayNextImage();
        }
    }
    else
    {
        event->ignore();
    }
}
/**
* Opens comment Edit Window
*/
void PictureManager::editComment()
{
    if (this->listWidget->selectedItems().count()>0)
    {
        CommentDialog dialog (this->listWidget, this);
        if (dialog.exec())
        {
            this->reLoadSlot();
        }
    }
}

/**
* Removes comment from selected Pictures
*/
void PictureManager::removeCommentSlot()
{
    QMessageBox msgBox;
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setText(tr("Are you sure to remove comments from selected pictures?"));
    msgBox.setWindowTitle(tr("Removing comments..."));
    msgBox.setIcon(QMessageBox::Question);
    if (msgBox.exec()==QMessageBox::Yes)
    {
        this->itsReader->setIsActive(false);
        new FileOperationsHandler(this, FileOperationsHandler::RemoveComments, this->filesOperations->fillFileList());
    }
}

/**
* Manages closeEvent
*/
void PictureManager::closeEvent(QCloseEvent * event )
{
    this->itsProperty->setWindowSize(this->size());
    this->itsProperty->setWindowPosition(this->pos());
    this->itsProperty->saveProperty();
    event->accept();
}

/**
* Manages PropertyDialog Open Event. Opens PropertyDialog
*/
void PictureManager::PropertyDialogOpenSlot()
{
    PropertyDialog dialog(this->itsProperty);
    dialog.exec();
}

/**
* returns itsProperty parameter
* @return Property
*/
Property* PictureManager::getItsProperty() const
{
    return itsProperty;
}
/**
* Manages Sorting Method changes Event
*/
void PictureManager::sortingMethodChangedSlot(int index)
{
    this->itsProperty->setSortMethod((Property::SortMethod)index);
    this->reLoadSlot();
}

/**
* Returns current directory
*/
QDir* PictureManager::getCurDir() const
{
    return curDir;
}

/**
* Handles make directory Action
*/
void PictureManager::makeDirectorySlot()
{
    this->filesOperations->makeDirectory();
}

/**
* Returns poiter to image reader
*/
ImageReader* PictureManager::getItsReader() const
{
    return itsReader;
}

/**
* Handles save file slot
*/
void PictureManager::saveImageSlot()
{
    if (this->isPresentationMode)
    {
        new FileOperationsHandler(this, FileOperationsHandler::SaveTransformedImage, this->filesOperations->fillFileList(), this->itsLoader->getActionList());
        this->itsLoader->setCurrentChangedFalse();
    }
}

/**
 * Returns Loader class
 * @return ImageLoader
 */
ImageLoader* PictureManager::getItsLoader() const
{
    return itsLoader;
}

/**
 * Returns classthat manages operation on images
 * @return 
 */
DisplayOperations * PictureManager::getDisplayOperations() const
{
    return this->displayOperations;
}

/**
 * Reloads Browser widget
 */
void PictureManager::reLoadBrowser()
{
    if ( this->itsReader->active() )
    {
        this->itsReader->setIsActive ( false );
    }
    this->listWidget->clear();
    this->itsReader->setDir ( this->curDir );
    this->itsReader->readDirCondition.wakeAll();
    this->setWindowTitle ( tr ( "AliceViewer: " ) + this->curDir->absolutePath() );
    this->listView->setRootIndex(((QFileSystemModel*)this->listView->model())->index(curDir->absolutePath()));
}

/**
 * Returns class Event Hadler
 * @return 
 */
EventHandler* PictureManager::getEventHandler() const
{
    return itsEventHandler;
}

/**
 * Returns if program is in Album viewer mode
 * @return bool
 */
bool PictureManager::getIsAlbumViewer() const
{
    return isAlbumViewer;
}

/**
 * Sets if program is in Album View mode
 * @param theValue 
 */
void PictureManager::setIsAlbumViewer(bool theValue)
{
    isAlbumViewer = theValue;
    if(isAlbumViewer){

    } else {

    }
}

/**
 * Returns class that handles operation on files nad directories
 * @return 
 */
FilesOperations* PictureManager::getFilesOperations() const
{
    return filesOperations;
}


QTreeView* PictureManager::getTreeWidget() const
{
    return treeWidget;
}
